import time

import requests
import threading

from logger import log
from settings import settings


def send(measurement, tags, field, value):
    # weather,location=us-midwest temperature=82
    data = measurement + ','

    for key, val in tags.items():
        data += f"{key}={val},"
    data = data[:-1] + ' '  # Remove the last comma and add a space
    data += f"{field}={value}"

    try:
        if settings.vm1_server is not None:
            url = f"{settings.vm1_server}/write"
            response = requests.post(url, data)
            log.info(f"{url} post {data}, {response.status_code}")
            if response.status_code != 204:
                log.error(f"{url} post {data}, {response.text}")
        if settings.vm2_server is not None:
            url = f"{settings.vm2_server}/write"
            response = requests.post(url, data)
            log.info(f"{url} post {data}, {response.status_code}")
            if response.status_code != 204:
                log.error(f"{url} post {data}, {response.text}")
    except requests.exceptions.RequestException:
        log.error("metric post error")


def get_date_str(date):
    return date.strftime('%y%m%d%H%M%S')


def online(ms):
    def send_heartbeat():
        while True:
            send("client_temperature", {"deviceName": settings.code}, "online", 1)
            time.sleep(ms)

    # Start the heartbeat in a new thread
    threading.Thread(target=send_heartbeat, daemon=True).start()


def temperature_callback(camera_name, location, temperature):
    tags = {
        "platformName": settings.platformName,
        "platformId": settings.platformId,
        "name": camera_name,
        "location": location
    }
    send("coal", tags, "temperature", temperature)


def init():
    # 在线心跳
    online(10)


# You can use the following to export functions if needed
# __all__ = ['init', 'send', 'temperature_callback']
if __name__ == '__main__':
    while True:
        send("coal", {"deviceName": "test"}, "temperature", 25)
        time.sleep(10)
